package org.baicaix.game.warworms.weapon {
	import com.worms.map.BattleMap;

	import org.baicaix.game.warworms.missile.Missile;
	import org.baicaix.pool.ObjectPoolManager;

	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.utils.Timer;

	/**
	 * 1 决定发射方向
	 * 2 力度
	 * 2 发射但要可以替换
	 * @author baicaix
	 */
	public class Weapon extends Sprite {
		
		private var shotSpeedBar : ShotSpeedBar; 
		private var shotSpeedTimer : Timer;
		private var worm : BitmapData;
		
		private var fireTimer: Timer;
		
		public function Weapon() {
			
			fireTimer = new Timer(70);
			fireTimer.addEventListener(TimerEvent.TIMER, enterFrameHandler);
			fireTimer.start();
			
			var wormSprite : Worm = this.addChild(new Worm()) as Worm;
			worm = new BitmapData(wormSprite.width, wormSprite.height);
			worm.draw(wormSprite, new Matrix(1, 0, 0, 1, wormSprite.x, wormSprite.y));
			
			this.graphics.beginFill(0x99cc00);
			this.graphics.drawCircle(150, 0, 10);
			this.graphics.endFill();
			
			
			shotSpeedBar = this.addChild(new ShotSpeedBar()) as ShotSpeedBar;
			
			shotSpeedTimer = new Timer(70);
			shotSpeedTimer.addEventListener(TimerEvent.TIMER, speedAdd);
			function speedAdd(event : TimerEvent) : void {
				shotSpeedBar.speed += 5;
			}
		}

		private function enterFrameHandler(event : TimerEvent) : void {
			move(0, 1);
		}

		
		public function fire() : void {
			Missile(stage.addChild(ObjectPoolManager.getInstance().get(Missile))).fire(this.rotation, x, y, shotSpeedBar.speed);
			shotSpeedTimer.stop();
			shotSpeedBar.speed = 0;
		}

		private var zhongli : Number = 1;
		public function move(vx : Number, vy : Number) : void {
			vy += zhongli;
			if(!hitTest(vx, vy)) {
				this.x += vx;
				this.y += vy;
			}
		}

		private function hitTest(vx : Number, vy : Number) : Boolean {
			var p : Point = new Point(this.x + vx, this.y + vy);
			p = BattleMap.getInstance().globalToLocal(p);
			return BattleMap.getCurrentBitmapData().hitTest(new Point(), 255, worm, p, 255);
		}
		
		public function rotate(angle : Number) : void {
			rotation += angle;
		}
		
		
		public function hold() : void {
			shotSpeedTimer.start();
		}
	}
}

import flash.display.Sprite;

class Worm extends Sprite {

	public function Worm() {
		this.graphics.beginFill(0x99cc00);
		this.graphics.drawCircle(x, y, 3);
		this.graphics.endFill();
	}
}
